/** 
* GroupVideoChat.js
*
*
*
**/

        
        var apiKey = null; 
        $.ajax({
                type : "POST",
                url : "get-api-key",
                success : function(data) {
                        apiKey = ""+data;
                }
        }); // OpenTok sample API key. Replace with your own API key.
        var sessionId = null; // Replace with your session ID.
        var token = null;
        $.ajax({
                type : "POST",
                url : "get-api-secret",
                success : function(data) {
                        token = ""+data;
                }
        }); // Token Should not be hard-coded.
                // Add to the page using the OpenTok server-side libraries.
        var session;
        //var publisher;
        var subscribers = {};
        var publisher = null;
        var deviceManager;
        var devicePanel;
        var panelShowing = false;

        var PUBLISHER_WIDTH = 220;
        var PUBLISHER_HEIGHT = 165;
        // Un-comment either of the following to set automatic logging and exception handling.
        // See the exceptionHandler() method below.
        // TB.setLogLevel(TB.DEBUG);
        TB.addEventListener("exception", exceptionHandler);
        TB.setLogLevel(TB.DEBUG); // Set this for helpful debugging messages in console
        
        
        
        function initializeSession(){
                
                if (TB.checkSystemRequirements() != TB.HAS_REQUIREMENTS) {
                        alert("You don't have the minimum requirements to run this application."
                                        + "Please upgrade to the latest version of Flash.");
                } else {
                        sessionId = $('#session-id').val();
                        //The initial state is ""
                        if(sessionId == ""){
                                alert("Please Request a Session Id");
                                return false;
                        }
                                
                        
                        session = TB.initSession(sessionId);    // Initialize session
                        $('#req-id-btn').val("Close Session");
                        
                        // Add event listeners to the session
                        session.addEventListener('sessionConnected', sessionConnectedHandler);
                        session.addEventListener('sessionDisconnected', sessionDisconnectedHandler);
                        session.addEventListener('connectionCreated', connectionCreatedHandler);
                        session.addEventListener('connectionDestroyed', connectionDestroyedHandler);
                        session.addEventListener('streamCreated', streamCreatedHandler);
                        session.addEventListener('streamDestroyed', streamDestroyedHandler);
                        
                        $('#form-status').html("Sala creada, puedes compartir el ID de Sala con tus amigos.<br> Para que el resto te vea y/o escuche activa tu audio/video");
                        $('#bottom-bar').fadeIn();
                }
                
        }



//--------------------------------------
//  LINK CLICK HANDLERS
//--------------------------------------

/*
If testing the app from the desktop, be sure to check the Flash Player Global Security setting
to allow the page from communicating with SWF content loaded from the web. For more information,
see http://www.tokbox.com/opentok/build/tutorials/helloworld.html#localTest
*/
        function connect() {
                token = 'devtoken';
                session.connect(apiKey, token);
                $('#status-logger').val("Connected to Session");
    			$('#intro').fadeOut();
                $('#friends-grid').fadeIn();
        }
        
        function disconnect() {
                session.disconnect();
                $('#disconnect-btn').fadeOut();
                $('#publish-btn').fadeOut();
                $('#unpublish-btn').fadeOut();
        }
        
        // Called when user wants to start publishing to the session
        function startPublishing() {
                if (!publisher) {
                        var parentDiv = document.getElementById("myCamera");
                        var publisherDiv = document.createElement('div'); // Create a div for the publisher to replace
                        publisherDiv.setAttribute('id', 'opentok_publisher');
                        parentDiv.appendChild(publisherDiv);
                        publisher = session.publish(publisherDiv.id); // Pass the replacement div id to the publish method
                        $('#unpublish-btn').fadeIn();
                        $('#publish-btn').fadeOut();
                }
        }
        
        function stopPublishing() {
                if (publisher) {
                        session.unpublish(publisher);
                }
                publisher = null;
        
                $('#publish-btn').fadeIn();
                $('#unpublish-btn').fadeOut();
        }

//--------------------------------------
//  OPENTOK EVENT HANDLERS
//--------------------------------------

        function sessionConnectedHandler(event) {
                // Subscribe to all streams currently in the Session
                for (var i = 0; i < event.streams.length; i++) {
                        addStream(event.streams[i]);
                }
                $('#disconnect-btn').fadeIn();
                $('#publish-btn').fadeIn();
                $('#connect-btn').fadeOut();
        }
        
        function streamCreatedHandler(event) {
                // Subscribe to the newly created streams
                for (var i = 0; i < event.streams.length; i++) {
                        addStream(event.streams[i]);
                }
        }
        
        function streamDestroyedHandler(event) {
                // This signals that a stream was destroyed. Any Subscribers will automatically be removed.
                // This default behaviour can be prevented using event.preventDefault()
        }
        
        function sessionDisconnectedHandler(event) {
                // This signals that the user was disconnected from the Session. Any subscribers and publishers
                // will automatically be removed. This default behaviour can be prevented using event.preventDefault()
                publisher = null;
        
                $('#connect-btn').fadeIn();
                $('#disconnect-btn').fadeOut();
                $('#publish-btn').fadeOut();
                $('#unpublish-btn').fadeOut();
        }
        
        function connectionDestroyedHandler(event) {
                // This signals that connections were destroyed
        }
        
        function connectionCreatedHandler(event) {
                // This signals new connections have been created.
        }

/*
If you un-comment the call to TB.addEventListener("exception", exceptionHandler) above, OpenTok calls the
exceptionHandler() method when exception events occur. You can modify this method to further process exception events.
If you un-comment the call to TB.setLogLevel(), above, OpenTok automatically displays exception event messages.
*/
        function exceptionHandler(event) {
                alert("Exception: " + event.code + "::" + event.message);
        }

//--------------------------------------
//  HELPER METHODS
//--------------------------------------

        var CAMERAS_MAX_COLUMNS = 5;    // Table is 5x10 = 50 people.
        var CAMERAS_MAX_ROWS = 10;      // First cell is the session's owner. The rest are FCFS/FIFO treated.
        
        function addFriendToTable(tableRoot,subscriberDiv){
        	var totalFriends = suscribers.length;
        	var lastFriendRow = $('div[id*="subscribers"] div[style*="display:table-row;"]:last');
        	
        	suscriberDiv.css('display:table-cell');
        	suscriberDiv.attr("onclick","javascript: $('"+subsriberDiv.id+"').dialog();");
        	if(totalFriends % 5 == 0 ){
        		lastFriendRow = document.createElement('div');
        		lastFriendRow.css('display:table-row;');
        		tableRoot.appendChild(lastFriendRow);
        	}
        	
        	
        	lastFriendRow.appendChild(suscriberDiv);
        	
        }
        
        
        function addStream(stream) {
                // Check if this is the stream that I am publishing, and if so do not publish.
                if (stream.connection.connectionId == session.connection.connectionId) {
                        return;
                }
                var subscriberDiv = document.createElement('div'); // Create a div for the subscriber to replace
                subscriberDiv.setAttribute('id', stream.streamId); // Give the replacement div the id of the stream as its id.
                /** put the suscribers in a table */
                var tableRoot = $('#subscribers'); //using jquery for this call
                addFriendToTable(tableRoot,subscriberDiv);
                document.getElementById("subscribers").appendChild(subscriberDiv);
                subscribers[stream.streamId] = session.subscribe(stream, subscriberDiv.id);
        }
        
        /*function show(id) {
                document.getElementById(id).style.display = 'block';
        }
        
        function hide(id) {
                document.getElementById(id).style.display = 'none';
        }*/

        function toggleDevicePanelDialog(){
                if(panelShowing){
                        if (devicePanel) {
                                        deviceManager.removePanel(devicePanel);
                                }
                        $('#devicePanelContainer').dialog('close');
                        panelShowing = false;
                }else {
                                var newdiv = document.createElement("div");
                                newdiv.id = "devicePanel";
                                document.getElementById("devicePanelInset").appendChild(newdiv);
                                if (deviceManager == null) {
                                        deviceManager = TB.initDeviceManager(apiKey);
                                }
                                // Here we are hiding the default close button, and implementing our own.
                                devicePanel = deviceManager.displayPanel("devicePanel", publisher, {"showCloseButton" : false});
                                document.getElementById("toggleDevicePanelLink").value = 'Hide Device Panel';
                                launchDialogById('devicePanelContainer','Configure Camera/Mic');
                                panelShowing = true;
                        }
                
                
        }
        
        /**
         * -----------------------
         *              My Functions
         * -----------------------
         * */
        
        function showExceptionPopup(type,message){
                $("<div><b>Error Message:</b> " + message + "</div>").dialog({ title : 'Error'});
        }
        
        function launchDialogById(id,title){
                $("#"+id).dialog({
                        title: title,
                        autoOpen: false,
                        modal:true,
                        draggable:true,
                        resizable:false,
                        width: 'auto',
                        minHeight: 50,
                        height: 'auto',
                        dialogClass: 'ui-jqdialog',
                        close: function(event,ui){ 
                                if(panelShowing){
                                                if (devicePanel) {
                                                        deviceManager.removePanel(devicePanel);
                                                }
                                        panelShowing = false;
                                        }
                        
                                if(id == "formDialog"){
                                                $('#session-id').removeAttr("disabled");
                                                $('#pass-token').removeAttr("disabled");
                                        }
                        },
                        closeOnEscape: true });
                
                $('#'+id).dialog('open');
        }

        function requestSessionId(){
                $.ajax({
                           type: "POST",
                           url: "create-session",
                           dataType: 'json',
                           success: function(data){
                             $('#session-id').val(data.session_id);
                             $('#pass-token').val(data.session_token);
                           }
                         });
                $('#req-id-btn').val("Initiate Session");
        }
        

        function requestTokenBySessionId(sessionId) {
                
                if($('#session-id').val() == "" || $('#session-id').val() == null){
                        showExceptionPopup("SessionException","Primero ingresa un ID de Sala");
                        return false;
                }
                
                $.ajax({
                        type : "POST",
                        url : "create-token",
                        dataType : 'json',
                        data : $('#session-id').val(),
                        success : function(data) {
                                $('#session-id').val(data.session_id);
                                $('#pass-token').val(data.session_token);
                        }
                });
        }
        
        function createNewSession(){
                if($('#req-id-btn').val() == "Join/Create New Session"){
                        if($('#session-id').val() == "" || $('#session-id').val() == null)
                                requestSessionId();
                        else
                                initializeSession();
                }else if($('#req-id-btn').val() == "Initiate Session"){
                        initializeSession();
                        $('#req-id-btn').attr("disabled",true);
                        $('#formDialog').dialog('close');
                }
                
        }
        
        function createNewRoom(){
                $('#session-id').attr("disabled",true);
                $('#pass-token').attr("disabled",true);
                launchDialogById('formDialog','Nueva Sala');
        }
        
        function enterRoom(){
                $('#pass-token').attr("disabled",true);
                launchDialogById('formDialog','Entrar en una Sala');
        }
        
        function svcStatus(){
        	launchDialogById('statusDialog','Información de la Sala');
        	$('#friends-connected').html(subscribers.length);
        	$('#myCamera-status').html();
        	$('#session-id-status').html($('#session-id').val());
        }
        